package com.dingwen.spsest.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;

/**
 * 验证码 controller
 *
 * @author dingwen
 * 2021.05.19 17:15
 */
@RestController
@RequestMapping("/code")
@Slf4j
public class CodeController {
    public static final String CODE_KEY = "code";

    /**
     * 获取验证码
     *
     * @param session  会话
     * @param response 响应
     */
    @GetMapping("/get")
    public void get(HttpSession session, HttpServletResponse response) {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        session.setAttribute(CODE_KEY, captcha.getCode());
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);

        // 禁用页面缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        try {
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
